package com.kxr.literetrofit.network;

import android.text.TextUtils;

import com.kxr.literetrofit.BuildConfig;
import com.kxr.literetrofit.network.ssl.SSLFactory;
import com.kxr.literetrofit.network.ssl.SafeHouseHostVerifier;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by kongxr on 2019/3/11.
 * 网络工具初始化管理
 */
public class HttpManager {

    private static HttpManager mInstance;
    private static Retrofit retrofit;
    private static volatile ApiService request = null;
    private String baseUrl = ApiService.BASE_URL;

    private HttpManager() {
    }

    public static HttpManager getInstance() {
        if (mInstance == null) {
            synchronized (HttpManager.class) {
                if (mInstance == null) {
                    mInstance = new HttpManager();
                }
            }
        }
        return mInstance;
    }

    /**
     * 初始化
     * @param cerName https证书名 没有则传空
     */
    public void init(String cerName) {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        if (BuildConfig.DEBUG){
            HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.addInterceptor(logging);
        }
//        builder.addInterceptor(BaseInterceptor);
        builder.connectTimeout(15, TimeUnit.SECONDS);
        builder.readTimeout(30, TimeUnit.SECONDS);
        builder.writeTimeout(30, TimeUnit.SECONDS);
        if (!TextUtils.isEmpty(cerName)){
            builder.sslSocketFactory(Objects.requireNonNull(SSLFactory.getSSLContext(cerName)).getSocketFactory(), Objects.requireNonNull(SSLFactory.getTrustManagerFactory(cerName)));
            builder.hostnameVerifier(new SafeHouseHostVerifier());
        }
        builder.retryOnConnectionFailure(true);
        OkHttpClient client = builder.build();
        retrofit = new Retrofit.Builder()
                .client(client)
                .baseUrl(baseUrl)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }


    /**
     * 设置统一服务器base地址，调用后无需再调用init方法,如果不需要修改base地址（默认ApiService.BASE_URL），则只需调用init方法即可
     * @param mCerName 证书名称 没有则填空
     * @param baseUrl  服务器base地址
     */
    public void setBaseUrl(String mCerName, String baseUrl){
        this.baseUrl = baseUrl;
        init(mCerName);
    }

    public ApiService getRequest() {
        if (request == null) {
            synchronized (ApiService.class) {
                if (request == null) {
                    request = retrofit.create(ApiService.class);
                }
            }
        }
        return request;
    }
}
